package tech.yunland.shop.domain.service.report;

import com.moyuer.bsf.domain.model.HqlArgs;

import antlr.collections.impl.LList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import tech.yunland.shop.domain.dao.ChargeBillDao;
import tech.yunland.shop.domain.dao.IncomeDao;
import tech.yunland.shop.domain.dao.SaleBillDao;
import tech.yunland.shop.domain.dao.SaleBillEntryDao;
import tech.yunland.shop.domain.model.ChargeBill;
import tech.yunland.shop.domain.model.SaleBill;
import tech.yunland.shop.domain.model.SaleBillEntry;
import tech.yunland.shop.domain.model.report.Income;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收入报表service
 *
 * @author 王睿智<geekrize@gmail.com>
 */

@Service
public class IncomeService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private IncomeDao incomeDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private SaleBillDao saleBillDao;

	@Autowired
	private ChargeBillDao chargeBillDao;
	
	@Autowired
	private SaleBillEntryDao saleBillEntryDao;

	/**
	 * 月报
	 * 
	 * @param date
	 * @param organId
	 * @return
	 */
	public Map<String, Object> getMonth(Date date, String organId) {
		String sql = "select sum(cash) as cash,sum(deduction) as deduction,sum(charge) as cahrge from "
				+ "rpt_income where to_char(biz_date,'yyyy-MM')='" + date + "'and organ_id='" + organId
				+ "' GROUP BY organ_id,user_id ";
		return jdbcTemplate.queryForMap(sql);
	}

	/**
	 * 店铺总收入
	 * 
	 * @param organId
	 * @return
	 */
	@Cacheable(condition = "false" ,cacheNames="shopCache" )
	public Map<String, Object> getAll(String organId) {

		String sql = " select sum(income.amount) from "
				+ " (select c.received as amount,c.organ_id as organ_id from bill_charge c "
				+ " union all select s.received as amount,s.organ_id as organ_id from bill_sale s"
				+" left join bill_sale_entry bse on s.id=bse.owner_id left join goods g on g.id=bse.goods_id where bse.payment ='20'"
				+") income"
				+ " where income.organ_id='" + organId + "' ";

		return jdbcTemplate.queryForMap(sql);

	}

	/**
	 * 获取日报对象
	 *
	 * @param id
	 * @return Income
	 */
	public Income get(String id) {
		return incomeDao.get(id);
	}

	/**
	 * 根据参数生成 hql 查询语句
	 *
	 * @param organId
	 * @return
	 * @throws ParseException
	 */
	public HqlArgs genHqlArgs(String bizDate, String organId) throws ParseException {

		Map<String, Object> args = new HashMap<String, Object>();

		String hql = "from Income i where 1=1";
		if (organId != null) {
			hql += " and i.organId = :organId ";
			args.put("organId", organId);
		}
		if (bizDate != null) {

			hql += " and to_char(i.bizDate,'yyyy-MM-dd') = :bizDate ";
			args.put("bizDate", bizDate);
		}

		return new HqlArgs(hql, args);
	}

	/**
	 * 根据入参查询结果数量
	 *
	 * @param creatorId
	 * @return
	 * @throws ParseException
	 */
	@Cacheable(condition = "false",cacheNames="shopCache")
	public int getResultSize(String bizDate, String organId) throws ParseException {
		HqlArgs hqlArgs = genHqlArgs(bizDate, organId);
		return incomeDao.findByNamedParam(hqlArgs.getHql(), hqlArgs.getArgs()).size();
	}

	/**
	 * 根据入参查询结果集
	 *
	 * @param creatorId
	 * @param startIndex
	 * @param length
	 * @return
	 * @throws ParseException
	 */
	@Cacheable(condition = "false",cacheNames="shopCache")
	public List<Income> getResultInfo(String bizDate, String organId, Integer startIndex, Integer length)
			throws ParseException {
		HqlArgs hqlArgs = genHqlArgs(bizDate, organId);
		String hql = "select i " + hqlArgs.getHql() + " order by i.bizDate desc";

		return incomeDao.findByNamedParam(hql, startIndex, length, hqlArgs.getArgs());
	}

	/**
	 * 现金收入详情
	 * 
	 * @param dateType
	 * @param bizDate
	 * @param organId
	 * @return
	 */
	public List<SaleBill> getIncomeEntry(String type, String dateType, String bizDate, String organId) {

		List<SaleBill> listCash = new ArrayList<>();

		StringBuffer bufferSQL = new StringBuffer();
		bufferSQL.append(" select  distinct s.id as id from bill_sale s ");
		bufferSQL.append(" left join bill_sale_entry se on s.id=se.owner_id ");
		// 判断取值跨度
		if (dateType.equals("year")) {
			bufferSQL.append(" where to_char(s.bizdate,'yyyy')='" + bizDate.substring(0, 4) + "'  ");
		} else if (dateType.equals("month")) {
			bufferSQL.append(" where to_char(s.bizdate,'yyyy-MM')='" + bizDate.substring(0, 7) + "'  ");
		} else if (dateType.equals("day")) {
			bufferSQL.append(" where to_char(s.bizdate,'yyyy-MM-dd')='" + bizDate.substring(0, 10) + "'  ");
		}

		// 判断支付方式
		if (type.equals("cash")) {
			bufferSQL.append(" and se.payment = '20' ");
		} else if (type.equals("deduction")) {
			bufferSQL.append(" and se.payment in ('10','40')  ");
		}

		bufferSQL.append(" and s.state <> -1 and se.state <> -1 ");

		bufferSQL.append(" and organ_id='" + organId + "' order by s.id ");

		List<Map<String, Object>> saleBillIds = jdbcTemplate.queryForList(bufferSQL.toString());

		
		BigDecimal received = BigDecimal.ZERO;
		for (Map<String, Object> salesMaps : saleBillIds) {
			SaleBill saleBill = new SaleBill();
			saleBill = saleBillDao.get(salesMaps.get("id").toString());
			listCash.add(saleBill);
		}
		return listCash;
	}

	/**
	 * 充值收入详情
	 * 
	 * @param dateType
	 * @param bizDate
	 * @param organId
	 * @return
	 */
	public List<ChargeBill> getChargeEntry(String dateType, String bizDate, String organId) {

		List<ChargeBill> listCharge = new ArrayList<>();
		StringBuffer bufferSQL = new StringBuffer();
		bufferSQL.append(" select c.id as id from bill_charge c ");

		if (dateType.equals("year")) {

			bufferSQL.append(" where to_char(c.bizdate,'yyyy')='" + bizDate.substring(0, 4) + "' ");
		} else if (dateType.equals("month")) {
			bufferSQL.append(" where to_char(c.bizdate,'yyyy-MM')='" + bizDate.substring(0, 7) + "' ");
		} else if (dateType.equals("day")) {
			bufferSQL.append(" where to_char(c.bizdate,'yyyy-MM-dd')='" + bizDate.substring(0, 10) + "' ");
		}
		bufferSQL.append(" and organ_id='" + organId + "' order by c.bizDate desc   ");

		List<Map<String, Object>> chargeBillIds = jdbcTemplate.queryForList(bufferSQL.toString());

		for (Map<String, Object> chargesMaps : chargeBillIds) {
			ChargeBill chargeBill = new ChargeBill();
			chargeBill = chargeBillDao.get(chargesMaps.get("id").toString());
			listCharge.add(chargeBill);
		}

		return listCharge;
	}

	/**
	 * 消费收入详情
	 * 
	 * @param dateType
	 * @param bizDate
	 * @param organId
	 * @return
	 */
	public List<SaleBill> getDeductionEntry(String dateType, Date bizDate, String organId) {

		List<SaleBill> listDeduction = new ArrayList<>();

		return listDeduction;
	}

	/**
	 * 桌面端店铺日报(扣费/充值/现金)详情
	 * 
	 * @param type
	 * @param dateType
	 * @param bizDate
	 * @param organId
	 * 
	 * @return  List<Map<String, Object>> 
	 */
	public List<Map<String, Object>> getIncomeDesktopEntry(String type,String dateType, String bizDate, String organId,Integer page,Integer rows,String returnType){

		return incomeDao.getIncomeDesktopEntry(type, dateType, bizDate, organId,page, rows,returnType);
		
	}


}